<?php

namespace catchAdmin\api\controller;

use cainiao\api\v1\Link;
use catcher\CatchResponse;
use catcher\Code;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;
use think\helper\Str;
use think\Request;
/*
 * 菜鸟仓库
 * */
class Houniao extends Index
{

    public function houniaoService(Request $request)
    {

        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post('data');
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('HouNiao',json_encode($data,JSON_UNESCAPED_UNICODE));

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token

            if(!$request->has('data','post')){
                return $this->commonReturn('HouNiao',['code'=>Code::FAILED, 'msg'=>'缺少data']);
            }

            //处理data
            $data = json_decode($data,true);
            if(!$data||!is_array($data)){
                return $this->commonReturn('HouNiao',['code'=>Code::FAILED, 'msg'=>'data格式错误']);
            }

            //方法分发
            switch ($serviceType)
            {
                //接收订单
                case 'push':
                    $result = $this->push($data);
                    break;
                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn("HouNiao:" . $serviceType,$result);

        } catch (\Exception $exception) {
            return $this->commonReturn("HouNiao:" . $serviceType,['code'=>Code::FAILED, 'msg'=>$exception->getMessage()]);

        }

    }

    //候鸟推送
    protected function push($data)
    {
        $orderData = [];//主订单信息
        $orderSonData = [];//子订单信息

        //订单字段
        $orderKeys = ['username','user_phone','area_id','user_address','order_id','order_goods'];

        //订单商品字段
        $goodsKeys = ['goods_spu','sku_id','goods_num'];

        $msg = "";
        foreach ($data as $key => $value){
            $checkValueResult = $this->check_fields($value, $orderKeys,true);//验证字段
            //判断参数
            if(!is_array($checkValueResult)){
                $msg = 'data['.$key .']'.$checkValueResult;
                break;
            }
            $flag = Db::table('db_customs_hn_order')
                ->field('id')
                ->where(['order_id' => $value['order_id'], 'deleted_at' => 0, 'tenant_id' => $this->merchantInfo['tenant_id']])
                ->find();
            if($flag){
                $msg = '订单号'.$value['order_id'].'已存在';
                break;
            }
            foreach ($value['order_goods'] as $k => &$v){
                $checkVResult = $this->check_fields($v, $goodsKeys,true);//验证字段
                //判断参数
                if(!is_array($checkVResult)){
                    $msg = 'data['.$key .'],'.'order_goods['.$k .'],'.$checkVResult;
                    break 2;
                }

//                $v['order_id'] = $value['order_id'];
                $orderSonData[] = $v;
            }
            $value['tenant_id'] = $this->merchantInfo['tenant_id'];//电商商户
            unset($value['goodsInfo']);
            $orderData[] = $value;
            unset($value);
        }

        //dd($orderData);

        if($msg !== ""){
            return [ 'code'=>Code::FAILED , 'msg'=> $msg ];
        }

        if(count($orderData)>0 && count($orderSonData)>0){
            foreach ($orderData as &$value){
                //dd($value);
                $temp = [];
                $temp['tenant_id'] = $value['tenant_id'];
                $temp['created_at'] = time();
                $temp['updated_at'] = time();
                $temp['order_id'] = $value['order_id'];//订单iD
                $temp['username'] = $value['username'];//收件人名字
                $temp['id_card'] = $value['id_card'] ?? '';//收件人身份证
                $temp['user_phone'] = $value['user_phone'] ?? '';//收件人手机
                $temp['declarer'] = $value['declarer'] ?? '';//订购人
                $temp['declarer_id_card'] = $value['declarer_id_card'] ?? '';//订购人身份正
                $temp['amount_freight'] = $value['amount_freight'] ?? '';//运费
                $temp['amount_discount'] = $value['amount_discount'] ?? '';//优惠金额
                $temp['pay_no'] = $value['pay_no'] ?? '';//支付交易号
                $temp['create_time'] = $value['create_time'] ?? '';//支付交易号
                $temp['pay_time'] = $value['pay_time'] ?? '';//支付交易号

                //$temp['area_id'] =
                $isActiveAreaId = Db::table('db_syst_sync_areas')->where('pid',$value['area_id'])->count();
                $isActiveAreaId2 = Db::table('db_syst_sync_areas')->where('area_id',$value['area_id'])->find();

                if($isActiveAreaId > 0 || empty($isActiveAreaId2)){
                    return [ 'code'=>Code::FAILED , 'msg'=> '区域ID不存在，或者区域ID不是最下级'];
                }
                $temp['area_id'] = $value['area_id'] ?? '';//区县ID
                $temp['user_address'] = $value['user_address'] ?? '';//详细地址
                $temp['remark'] = $value['remark'] ?? '';//备注
                $temp['order_goods'] = json_encode($value['order_goods']);

                //扩展数据
                $temp['_ext_data'] = json_encode(array_merge($temp,$value));
                $value = $temp;
            }

            foreach ($orderSonData as &$value){
                $temp = [];
//                $temp['tenant_id'] = $value['tenant_id'];
//                $temp['order_id'] = $value['order_id'];
//                $temp['productId'] = $value['goods_spu'] . ',' . $value['sku_id'];
//                $temp['num'] = $value['goods_num'];
                $goods_info = Db::table('db_syst_sync_goods_rule sr')
                    ->field('sr.sku_name,sg.goods_name')
                    ->leftJoin('db_syst_sync_goods sg','sr.goods_id = sr.goods_id')
                    ->where('sr.goods_spu',$value['goods_spu'])
                    ->where('sr.goods_sku',$value['sku_id'])
                    ->find();
                if(!$goods_info){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品不存在该spu或sku' ];
                }

                $temp['goods_name'] = $goods_info['goods_name'] . $goods_info['sku_name'];
                $value = $temp;
            }

            // dd($orderData,$orderSonData);

            // 启动事务
            Db::startTrans();
            try {
                $res1 = Db::table('db_customs_hn_order')->limit(200)->insertAll($orderData);
//                $res2 = Db::table('db_customs_orderlist')->limit(200)->insertAll($orderSonData);
                if($res1){
                    // 提交事务
                    Db::commit();
                    return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=>[]];
                }else{
                    Db::rollback();
                    return [ 'code'=>Code::FAILED , 'msg'=> '新增失败'];
                }

            } catch (\Exception $e) {

                return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
                // 回滚事务
                Db::rollback();
            }
        }else{
            return [ 'code'=>Code::FAILED , 'msg'=> '没有订单或商品数据'];

        }
    }

}